#!/bin/sh
## java env
## 设置jdk环境
export JAVA_HOME=/usr/local/jdk/jdk1.8.0_202
export JRE_HOME=$JAVA_HOME/jre

## exec shell name
##EXEC_SHELL_NAME=$1\.sh
## service name
SERVICE_NAME=$1
CONFIG_PROFILE=$2
## jar包方式启动，修改路径为jar所在路径
SERVICE_DIR=/data/eightroes
JAR_NAME=$SERVICE_NAME\.jar
PID=pid/$SERVICE_NAME\.pid
WORK_DIR=$SERVICE_DIR/work

#function start
start(){
	  cd $WORK_DIR
	  if [ ! -d "logs" ]; then
		  mkdir logs
	  fi

	  nohup $JRE_HOME/bin/java -XX:MetaspaceSize=512m -XX:MaxMetaspaceSize=512m -Xms512m -Xmx512m -Xmn512m -jar $JAR_NAME --spring.profiles.active=$CONFIG_PROFILE >logs/$SERVICE_NAME.out 2>&1 &
	  
	  echo $! > $SERVICE_DIR/$PID
	  echo "#### start $SERVICE_NAME"
}

# function stop
stop(){
	  cd $WORK_DIR
	  if [ -f "$SERVICE_DIR/$PID" ]; then
              kill `cat $SERVICE_DIR/$PID`
              rm -rf $SERVICE_DIR/$PID
      fi
      echo "#### stop $SERVICE_NAME"
      sleep 6
      TEMP_PID=`ps -ef | grep -w "$SERVICE_NAME" | grep "java" | awk '{print $2}'`
      if [ "$TEMP_PID" == "" ]; then
          echo "#### $SERVICE_NAME process not exists or stop success"
      else
          echo "#### $SERVICE_NAME process pid is:$TEMP_PID ."
          kill -9 $TEMP_PID
      fi
}

# function clean
clean(){
	  cd $WORK_DIR
      if [ ! -d "lastDeploy" ]; then
         mkdir lastDeploy
      else
         rm lastDeploy/$SERVICE_NAME*
      fi
      if [ -f "$JAR_NAME" ]; then
         mv $JAR_NAME lastDeploy
      fi    
}

case "$3" in

	  start)
	  start
		  ;;

	  stop)
	  stop
		  ;;

	  restart)
		  stop
		  sleep 2
		  start
		  echo "#### restart $SERVICE_NAME"
		  ;;

	  clean)
	  stop
	  sleep 2
	  clean
	  echo "#### clean $SERVICE_NAME"
	  ;;

	  *)
		 ## restart
		 stop
		 sleep 2
		 start
		 ;;

	esac
exit 0
